package org.fjsei.yewu.aop;

import org.fjsei.yewu.config.datasource.CockroachDBHealthIndicator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class DatabaseClusterMonitor {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseClusterMonitor.class);

    private final CockroachDBHealthIndicator healthIndicator;
    private volatile boolean serviceEnabled = true;

    public DatabaseClusterMonitor(@Lazy CockroachDBHealthIndicator healthIndicator) {
        this.healthIndicator = healthIndicator;
    }

    @EventListener
    public void handleDatabaseHealthEvent(CockroachDBHealthIndicator.DatabaseHealthEvent event) {
        if (!event.isHealthy()) {
            logger.error("Database health event received: {}", event.getError().getMessage());
            enableMaintenanceMode();
        } else {
            logger.info("Database recovery event received, consecutive checks: {}",
                    healthIndicator.getConsecutiveHealthyChecks());
        }
    }

    public void enableMaintenanceMode() {
        if (!serviceEnabled) {
            return;
        }

        serviceEnabled = false;
        healthIndicator.setClusterHealthy(false);
        healthIndicator.setMaintenanceMode(true);

        // 紧急停止所有后台任务
//        if (taskStopper != null) {
//            taskStopper.emergencyStopAllTasks();
//        }

        logger.warn("=== ENTERING MAINTENANCE MODE ===");
        logger.warn("All new requests will be rejected and background tasks stopped");
    }

    public void disableMaintenanceMode() {
        if (serviceEnabled) {
            return;
        }

        serviceEnabled = true;
        healthIndicator.setClusterHealthy(true);
        healthIndicator.setMaintenanceMode(false);

        // 恢复后台任务
//        if (taskStopper != null) {
//            taskStopper.resumeAllTasks();
//        }

        logger.info("=== EXITING MAINTENANCE MODE ===");
        logger.info("Service is now accepting requests");
    }

    public boolean isServiceEnabled() {
        return serviceEnabled;
    }

    public String getStatus() {
        if (!serviceEnabled && healthIndicator.isRecoveryPending()) {
            return "RECOVERY_PENDING";
        }
        return serviceEnabled ? "OPERATIONAL" : "MAINTENANCE_MODE";
    }

//    public Map<String, Object> getDetailedStatus() {
//        Map<String, Object> status = new HashMap<>();
//        status.put("serviceEnabled", serviceEnabled);
//        status.put("maintenanceMode", !serviceEnabled);
//        status.put("recoveryPending", healthIndicator.isRecoveryPending());
//        status.put("consecutiveHealthyChecks", healthIndicator.getConsecutiveHealthyChecks());
//        status.put("timestamp", Instant.now());
//        return status;
//    }
}
